package com.jues.huichain.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.jues.huichain.R;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


import health.lm.com.component_base.base.event.IBus;
import health.lm.com.component_base.base.event.RxBusImpl;
import health.lm.com.network.callback.SimpleCallBack;
import health.lm.com.order.entity.PayResultEntity;
import health.lm.com.order.model.OrderModel;

import static health.lm.com.component_base.base.application.BaseApplication.AppId;


public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
    public IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_result);

        api = WXAPIFactory.createWXAPI(this, AppId);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        if (resp.errCode == 0) {
            test();
        } else {
            this.finish();
            ToastUtils.showShort("微信支付失败");
        }
    }

    private void test() {
        String order_sn = SPUtils.getInstance().getString("order_sn");
        OrderModel.getInstance().checkPayState(order_sn, 1, new SimpleCallBack<PayResultEntity>() {
            @Override
            public void onSuccess(PayResultEntity entity) {
                if (entity !=null){
                    RxBusImpl.get().post(new IBus.AbsEvent() {
                        @Override
                        public int getTag() {
                            WXPayEntryActivity.this.finish();
                            return entity.getStatus();
                        }
                    });
                }
            }
        });
    }
}